//给定一个二叉树，原地将它展开为一个单链表。 
//
// 
//
// 例如，给定二叉树 
//
//     1
//   / \
//  2   5
// / \   \
//3   4   6 
//
// 将其展开为： 
//
// 1
// \
//  2
//   \
//    3
//     \
//      4
//       \
//        5
//         \
//          6 
// Related Topics 树 深度优先搜索 
// 👍 654 👎 0


package com.yun.leetcode.editor.cn;

public class FlattenBinaryTreeToLinkedList {
    public static void main(String[] args) {
        Solution solution = new FlattenBinaryTreeToLinkedList().new Solution();
        TreeNode node1 = new TreeNode(1);
        TreeNode node2 = new TreeNode(2);
        TreeNode node5 = new TreeNode(5);
        TreeNode node3 = new TreeNode(3);
        TreeNode node4 = new TreeNode(4);
        TreeNode node6 = new TreeNode(6);

        node1.left = node2;
        node1.right = node5;
        node2.left = node3;
        node2.right = node4;
        node5.right = node6;
        solution.flatten(node1);
        System.out.println(node1);
    }
//leetcode submit region begin(Prohibit modification and deletion)

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     * int val;
     * TreeNode left;
     * TreeNode right;
     * TreeNode() {}
     * TreeNode(int val) { this.val = val; }
     * TreeNode(int val, TreeNode left, TreeNode right) {
     * this.val = val;
     * this.left = left;
     * this.right = right;
     * }
     * }
     */
    class Solution {
        public void flatten(TreeNode root) {
            // 需要维护关系，就是给左节点放到右节点前面。
            // 先序位置做转移，需要从最左下开始转移
            // 1,null,2,3 是什么几把用例，起的肚子疼
//            if (root == null || root.left == null) {
//                return;
//            }
//
//            flatten(root.left);
//            TreeNode leftHead = root.left;
//            TreeNode leftTail = root.left;
//            TreeNode realRight = root.right;
//            if (root.right == null) {
//                root.right = leftHead;
//            } else {
//                while (leftTail.right != null) {
//                    leftTail = leftTail.right;
//                }
//                TreeNode tmp = root.right;
//                root.right = leftHead;
//                leftTail.right = tmp;
//            }
//            root.left = null;
//
//            flatten(realRight);
            if (root == null) return;

            flatten(root.left);
            flatten(root.right);

            /**** 后序遍历位置 ****/
            // 1、左右子树已经被拉平成一条链表
            TreeNode left = root.left;
            TreeNode right = root.right;

            // 2、将左子树作为右子树
            root.left = null;
            root.right = left;

            // 3、将原先的右子树接到当前右子树的末端
            TreeNode p = root;
            while (p.right != null) {
                p = p.right;
            }
            p.right = right;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}